package com.fanfq.itrack.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.fanfq.itrack.CustomMenu.OnMenuItemSelectedListener;
import com.fanfq.itrack.Constant;
import com.fanfq.itrack.CustomMenuItem;
import com.fanfq.itrack.Export;
import com.fanfq.itrack.Gps;
import com.fanfq.itrack.R;
import com.fanfq.itrack.model.Ride;
import com.fanfq.itrack.ui.RecordActivity.MyLocationListenner;
import com.fanfq.itrack.ui.RecordActivity.locationOverlay;
import com.fanfq.util.DBUtil;
import com.fanfq.util.GPSUtil;

public class RecordActivity extends Activity implements OnClickListener {
	
	private LocationManager mLocationManager;
	private Location mLocation;
	private Criteria mCriteria;
	private String provider;
	private Gps storeDate;//重复数据只保留一份
	
	
	// 定位相关
//	LocationClient mLocClient;
	LocationData locData = null;
//	public MyLocationListenner myListener = new MyLocationListenner();

	// 定位图层
	locationOverlay myLocationOverlay = null;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	MyLocationMapView mMapView = null; // 地图View
	private MapController mMapController = null;

	// UI相关
	OnCheckedChangeListener radioButtonListener = null;
	Button requestLocButton = null;
	boolean isRequest = false;// 是否手动触发请求定位
	boolean isFirstLoc = true;// 是否首次定位
	boolean isLocationClientStop = false;

	
	private boolean isStarted = false;
	private boolean isStatus = false;
	private RelativeLayout status;
	private RelativeLayout map_view;
	private TextView tv_status;
	private TextView tv_map;
	private TextView signal;
	private TextView time;
	private TextView distance;
	private TextView speed;
	private Button start;
	private double templon = 0;
	private double templat =0;
	private double distance_value = 0;
	private int pos = 0;
	private Timer timer;
	private int recLen = 0;
	private DBUtil mDBUtil;
	private String rideId;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				recLen++;
				time.setText(String.format("%02d:%02d:%02d", recLen / 3600,
						(recLen / 60) > 59 ? recLen / 3600 : recLen / 60,
						recLen % 60));
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.record);
		
		tv_status = (TextView) findViewById(R.id.tv_status);
		tv_map = (TextView) findViewById(R.id.tv_map);
		signal = (TextView) findViewById(R.id.signal);
		time = (TextView) findViewById(R.id.timer);
		distance = (TextView) findViewById(R.id.distance);
		speed = (TextView) findViewById(R.id.speed);
		start = (Button) findViewById(R.id.start);
		status = (RelativeLayout)findViewById(R.id.status);
		map_view = (RelativeLayout)findViewById(R.id.map_view);
		start.setOnClickListener(this);
		tv_status.setOnClickListener(this);
		tv_map.setOnClickListener(this);
		mDBUtil = new DBUtil(this);
		
		requestLocButton = (Button) findViewById(R.id.map_loc);
		OnClickListener btnClickListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 手动定位请求
				requestLocClick();
			}
		};
		requestLocButton.setOnClickListener(btnClickListener);

		// 地图初始化
		mMapView = (MyLocationMapView) findViewById(R.id.bmapView);
		mMapController = mMapView.getController();
		mMapView.getController().setZoom(14);
		mMapView.getController().enableClick(true);
		mMapView.setBuiltInZoomControls(true);
		// 创建 弹出泡泡图层
		createPaopao();

		// 定位初始化
//		mLocClient = new LocationClient(this);
		locData = new LocationData();
//		mLocClient.registerLocationListener(myListener);
//		LocationClientOption option = new LocationClientOption();
//		option.setOpenGps(true);// 打开gps
//		option.setCoorType("bd09ll"); // 设置坐标类型
//		option.setScanSpan(1000);
//		mLocClient.setLocOption(option);
//		mLocClient.start();
		
		initLocation();//初始化GPS定位

				
		//界面加载时添加绘制图层
		addLoc();
		addCustomElements();
	}
	
	/**
	 * @Title: initLocation
	 * @Description: GPS初始化
	 * @param void
	 * @return void    
	 * @throws 
	 */
	private void initLocation() {
		mLocationManager = (LocationManager)getSystemService(this.LOCATION_SERVICE);
		if (mLocationManager.isProviderEnabled(mLocationManager.GPS_PROVIDER)) {
			mCriteria = new Criteria();
			mCriteria.setAccuracy(Criteria.ACCURACY_COARSE);// 精度
			mCriteria.setAltitudeRequired(true);// 显示海拔
			mCriteria.setBearingRequired(true);// 显示方向
			mCriteria.setSpeedRequired(true);// 显示速度
			mCriteria.setCostAllowed(true);// 不允许有花费
			mCriteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
			provider = mLocationManager.getBestProvider(mCriteria, true); // 获取GPS信息
			// 位置变化监听,默认5秒一次,距离10米以上
			mLocationManager.requestLocationUpdates(provider, 1000, 0,
					locationListener);
		} else {
			showInfo(null, Constant.GPS_LOST);
		}
	}
	
	/**	 初始化GPS监听	 */
	private final LocationListener locationListener = new LocationListener() {
		public void onLocationChanged(Location arg0) {
			showInfo(getLastPosition(), Constant.GPS_AUTO_LOCAL);
		}
		public void onProviderDisabled(String arg0) {
			showInfo(null, Constant.GPS_LOST);
		}
		public void onProviderEnabled(String arg0) {
		}
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		}
	};
	
	/**
	 * @Title: getLastPosition
	 * @Description: 获取GPS数据
	 * @param void
	 * @return Gps    
	 * @throws 
	 */
	private Gps getLastPosition() {
		Gps result = new Gps();
		if(null != provider){
			mLocation = mLocationManager.getLastKnownLocation(provider);
		}
		if (mLocation != null) {
			result.setLatitude(mLocation.getLatitude());
			result.setLongitude(mLocation.getLongitude());
			result.setAltitude(mLocation.getAltitude());
			result.setBearing(mLocation.getBearing());
			result.setSpeed(mLocation.getSpeed());
			result.setTimestamp(mLocation.getTime());
		}
		return result;
	}
	
	/**
	 * @Title: showInfo
	 * @Description: debug GPS数据
	 * @param Gps cdata, int infotype
	 * @return void    
	 * @throws 
	 */
	private void showInfo(Gps cdata, int infotype) {
		if (cdata == null) {
			if (infotype == Constant.GPS_LOST) {
				Toast.makeText(this, "GPS功能已关闭", 1).show();
				Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		        startActivityForResult(intent,0); //此为设置完成后返回到获取界面
			}
		} else {
//			Toast.makeText(
//					this,
//					String.format("纬度:%f", cdata.getLatitude()) + ","
//							+ String.format("经度:%f", cdata.getLongitude())
//							+ "," + String.format("海拔:%f", cdata.getHigh())
//							+ "," + String.format("方向:%f", cdata.getDirect())
//							+ "," + String.format("速度:%f", cdata.getSpeed())
//							+ "," + String.format("GPS时间:%s", cdata.getGpsTime())
//							+ "," + String.format("数据类型:%d", cdata.getInfoType()), 1)
//					.show();
			//跟新页面的数据显示 todo
//			this.lat.setText(String.format("%f",cdata.getLatitude()));
//			this.lon.setText(String.format("%f",cdata.getLongitude()));
//			this.direct.setText(String.format("%f",cdata.getDirect()));
//			this.speed.setText(String.format("%f",cdata.getSpeed()));
//			this.high.setText(String.format("%f",cdata.getHigh()));
			
			
			
			if(null!=storeDate && storeDate.equals(cdata)){
				return ;
			}else if(cdata.getLatitude() !=0 && cdata.getLongitude()!=0){
				if(templon!=0&&templat!=0&&pos>1){
					//double sp = 6371004*Math.cos(Math.sin(templon)*Math.sin(cdata.getLongitude())+Math.cos(templon)*Math.cos(cdata.getLongitude())*Math.cos(templat-cdata.getLatitude()))*3.14/180;
					this.speed.setText(String.format("%.1f", (cdata.getSpeed() +storeDate.getSpeed())/2/1000*3600));
					if(cdata.getSpeed()!=0){
						distance_value += GPSUtil.getDistance(templat, templon, cdata.getLatitude(), cdata.getLongitude());
						this.distance.setText(String.format("%.1f", distance_value));
						if(isStarted)
						//添加折线
				        graphicsOverlay.setData(drawLine(templat, templon, cdata.getLatitude(), cdata.getLongitude()));
					}
				}
				templat = cdata.getLatitude();
				templon = cdata.getLongitude();
				
//				signal.setText("Satellite Count: "+getStarCount());
				if(isStarted){
					cdata.setDistance(distance_value);
					cdata.setFiltered(pos == 0 ? 1:0);
					cdata.setPos(pos++);
					cdata.setRide_id(rideId);
					cdata.setDevice_time(System.currentTimeMillis());
					cdata.setElapsed_time(recLen);
					
					this.mDBUtil.addGpsData(cdata);//数据存储
				}
								
				locData.latitude = templat;
				locData.longitude = templon;
				
				
				// 是手动触发请求或首次定位时，移动到定位点
				if (isRequest || isFirstLoc) {
					// 移动地图到定位点
					mMapController.animateTo(new GeoPoint(
							(int) (locData.latitude * 1e6),
							(int) (locData.longitude * 1e6)));
					isRequest = false;
				}
				// 首次定位完成
				isFirstLoc = false;
				
				// 更新定位数据
				myLocationOverlay.setData(locData);
				// 更新图层数据执行刷新后生效
				mMapView.refresh();
				
				//清除所有图层
		    	//mMapView.getOverlays().clear();//remove(graphicsOverlay);
//		    	addCustomElements();
//				addLoc();
				storeDate = cdata;

			}
		}
	}
	
	public void addLoc(){
		// 定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		// 修改定位数据后刷新图层生效
		mMapView.refresh();
	}
	
	GraphicsOverlay graphicsOverlay;
	/**
     * 添加点、线、多边形、圆、文字
     */
    public void addCustomElements(){
    	graphicsOverlay = new GraphicsOverlay(mMapView);
        mMapView.getOverlays().add(graphicsOverlay);
    	//添加折线
        graphicsOverlay.setData(drawLine());
        //执行地图刷新使生效
        mMapView.refresh();
    }
    
    public Graphic drawLine(double lat1,double lon1,double lat2,double lon2){
    	//构建线
  		Geometry lineGeometry = new Geometry();
  		//设定折线点坐标
  		GeoPoint[] linePoints = new GeoPoint[2];
		linePoints[0] = new GeoPoint((int)(lat1*1E6), (int)(lon1*1E6));
		linePoints[1] = new GeoPoint((int)(lat2*1E6), (int)(lon2*1E6));
		lineGeometry.setPolyLine(linePoints);
    	//设定样式
  		Symbol lineSymbol = new Symbol();
  		Symbol.Color lineColor = lineSymbol.new Color();
  		lineColor.red = 255;
  		lineColor.green = 0;
  		lineColor.blue = 0;
  		lineColor.alpha = 255;
  		lineSymbol.setLineSymbol(lineColor, 10);
  		//生成Graphic对象
  		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
  		return lineGraphic;
    }
    /**
     * 绘制折线，该折线状态随地图状态变化
     * @return 折线对象
     */
    public Graphic drawLine(){
    	//get gps by ride_id
    	List<Gps> list = mDBUtil.getGpsByRideId(rideId);
    	if(list.size()==0) return null;
    	//构建线
  		Geometry lineGeometry = new Geometry();
  		//设定折线点坐标
  		GeoPoint[] linePoints = new GeoPoint[list.size()];
  		int i = 0;
    	for(Gps l:list){
    		linePoints[i++] = new GeoPoint((int)(l.getLatitude()*1E6), (int)(l.getLongitude()*1E6));
    	}
    	lineGeometry.setPolyLine(linePoints);
    	//设定样式
  		Symbol lineSymbol = new Symbol();
  		Symbol.Color lineColor = lineSymbol.new Color();
  		lineColor.red = 255;
  		lineColor.green = 0;
  		lineColor.blue = 0;
  		lineColor.alpha = 255;
  		lineSymbol.setLineSymbol(lineColor, 10);
  		//生成Graphic对象
  		Graphic lineGraphic = new Graphic(lineGeometry, lineSymbol);
  		return lineGraphic;
    }

	/**
	 * 手动触发一次定位请求
	 */
	public void requestLocClick() {
		isRequest = true;
//		mLocClient.requestLocation();
		Toast.makeText(RecordActivity.this, "正在定位…", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 修改位置图标
	 * 
	 * @param marker
	 */
	public void modifyLocationOverlayIcon(Drawable marker) {
		// 当传入marker为null时，使用默认图标绘制
		myLocationOverlay.setMarker(marker);
		// 修改图层，需要刷新MapView生效
		mMapView.refresh();
	}

	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao() {
		viewCache = getLayoutInflater()
				.inflate(R.layout.custom_text_view, null);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);
		// 泡泡点击响应回调
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				Log.v("click", "clickapoapo");
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
		MyLocationMapView.pop = pop;
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || isLocationClientStop)
				return;
//			locData.latitude = location.getLatitude();
//			locData.longitude = location.getLongitude();
//			// 如果不显示定位精度圈，将accuracy赋值为0即可
//			locData.accuracy = location.getRadius();
//			locData.direction = location.getDerect();
//			// 更新定位数据
//			myLocationOverlay.setData(locData);
//			// 更新图层数据执行刷新后生效
//			mMapView.refresh();
//			// 是手动触发请求或首次定位时，移动到定位点
//			if (isRequest || isFirstLoc) {
//				// 移动地图到定位点
//				mMapController.animateTo(new GeoPoint(
//						(int) (locData.latitude * 1e6),
//						(int) (locData.longitude * 1e6)));
//				isRequest = false;
//			}
//			// 首次定位完成
//			isFirstLoc = false;
			
//			//update ui
			signal.setText("Satellite Count: "+location.getSatelliteNumber());
//			
//			if(templon!=0&&templat!=0&&pos>1){
//				//double sp = 6371004*Math.cos(Math.sin(templon)*Math.sin(cdata.getLongitude())+Math.cos(templon)*Math.cos(cdata.getLongitude())*Math.cos(templat-cdata.getLatitude()))*3.14/180;
//				speed.setText(String.format("%.1f", location.getSpeed()/1000*3600));
//				if(location.getSpeed()!=0){
//					distance_value += GPSUtil.getDistance(templat, templon, location.getLatitude(), location.getLongitude());
//					distance.setText(String.format("%.1f", distance_value/1000));
////					distance.setText(location.getTime());
//				}
//			}
//			templat = location.getLatitude();
//			templon = location.getLongitude();
//			
//			if(isStarted){
//				Gps cdata = new Gps();
//				cdata.setAltitude(location.getAltitude());
//				cdata.setLatitude(location.getLatitude());
//				cdata.setLongitude(location.getLongitude());
//				cdata.setBearing(location.getDerect());
//				cdata.setSpeed(location.getSpeed());
//				cdata.setDistance(distance_value);
//				cdata.setFiltered(pos == 0 ? 1:0);
//				cdata.setPos(pos++);
//				cdata.setRide_id(rideId);
//				cdata.setDevice_time(System.currentTimeMillis());
//				cdata.setTimestamp(location.getTime());
//				cdata.setElapsed_time(recLen);
//				
//				mDBUtil.addGpsData(cdata);//数据存储
//			}
//			//清除所有图层
//	    	mMapView.getOverlays().clear();//remove(graphicsOverlay);
//	    	addCustomElements();
//			addLoc();
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	// 继承MyLocationOverlay重写dispatchTap实现点击处理
	public class locationOverlay extends MyLocationOverlay {

		public locationOverlay(MapView mapView) {
			super(mapView);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected boolean dispatchTap() {
			// TODO Auto-generated method stub
			// 处理点击事件,弹出泡泡
			popupText.setBackgroundResource(R.drawable.popup);
			popupText.setText("我的位置");
			pop.showPopup(BMapUtil.getBitmapFromView(popupText), new GeoPoint(
					(int) (templat * 1e6),
					(int) (templon * 1e6)), 8);
			return true;
		}

	}

	@Override
	protected void onPause() {
		isLocationClientStop = true;
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		isLocationClientStop = false;
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
//		if (mLocClient != null)
//			mLocClient.stop();
//		isLocationClientStop = true;
		mLocationManager.removeUpdates(locationListener);
		timer.cancel(); //退出计时器
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_status:
			isStatus = true;
			status.setVisibility(View.VISIBLE);
			map_view.setVisibility(View.GONE);
			break;
		case R.id.tv_map:
			isStatus = false;
			status.setVisibility(View.GONE);
			map_view.setVisibility(View.VISIBLE);
			break;
		case R.id.start:
			if(isStarted){
				timer.cancel(); //退出计时器
				start.setText("Start");
				
				//recLen rideId update ride by rideid
				
				isStarted = false;
			}else{
				TimerTask task = new TimerTask() {
					public void run() {
						Message message = new Message();
						message.what = 1;
						handler.sendMessage(message);
					}
				};
				
				timer = new Timer();
				timer.schedule(task,1000, 1000); //延时1000ms后执行，1000ms执行一次
		        start.setText("Recording...");
		        isStarted = true;
		        
		        //add a ride
		        Ride ride = new Ride();
		        ride.setId(UUID.randomUUID().toString());
		        ride.setStart_timestamp(System.currentTimeMillis());
		        ride.setComments_count(0);
		        ride.setKudos_count(0);
		        ride.setUser_id("fan");
		        ride.setTitle("this is title");
		        mDBUtil.addRide(ride);
				
		        rideId = ride.getId();
		        pos = 0;
			}
			break;
		default:
			break;
		}
	}  


}
